<?php

namespace App\Jobs;

use App\Models\Activity;
use App\Models\Common\Common;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LotteryDraw implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $act_id;

    /**
     * Create a new job instance.
     *
     * @param int $act_id
     * @return void
     */
    public function __construct($act_id)
    {
        $this->act_id = $act_id;
    }

    /**
     * Execute the job.
     * 霸王餐活动预开奖(预开奖后到开奖之前，可以在运营端修改中奖人)
     *
     * @return void
     */
    public function handle()
    {
        $act_id = $this->act_id;
        Log::debug('霸王餐活动预开奖：', ['act_id'=>$act_id]);

        // 查询当前活动
        try {
            DB::beginTransaction();

            $activity = DB::table('lottery_activity')->where('act_id', '=', $act_id)->lockForUpdate()->first();
            $activity = json_decode(json_encode($activity), true);
            // 检查是否已经关闭活动

            if ($activity['is_stop']) {
                DB::rollBack();
                Log::debug('霸王餐活动预开奖：活动被关闭', $activity);
                return;
            }

            // 如果当前活动状态不是正在进行，根据活动状态记录日志
            if($activity['status'] !== Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_BEFORE){
                switch ($activity['status']){
                    case Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_CANCEL: // 活动已被取消
                        $info = '霸王餐活动预开奖：活动已被取消';
                        break;
                    case Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_PRE: // 正在开奖：取消
                        $info = '霸王餐活动预开奖：活动已开奖';
                        break;
                    default: // 已开奖、已完成：取消
                        $info = '霸王餐活动预开奖：活动已开奖';
                }
                Log::debug($info,$activity);
                DB::rollBack();
                return;
            }

            // 随机查一个参与人，如果没有直接结束活动
            $participates = Activity::findParticipate($act_id);
            if(!$participates){
                Activity::drawCancel($activity,'活动超时无人参与');
                DB::commit();
                return;
            }

            // 更新用户为预中奖状态
            DB::table('lottery_users_draw')
                ->where('participate_id','=',$participates['participate_id'])
                ->update([
                    'status'=>Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_WINING,
                    'win_at'=>date('Y-m-d H:i:s'),
                    'cancel_at'=>date('Y-m-d H:i:s',time() + Period::getSetting('LOTTERY_NEXT_MEMBER')),
                ]);

            // 修改开奖状态为正在开奖
            DB::table('lottery_activity')
                ->where('act_id','=',$activity['act_id'])
                ->update(['status' => Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_PRE]);

            // 超时换下一位
            $end_time = date('Y-m-d H:i:s', time() + Period::getSetting('LOTTERY_NEXT_MEMBER'));
            $delay = Activity::drawTime($end_time);
            LotteryDrawOvertime::dispatch($participates['participate_id'])->delay($delay);

            DB::commit();

            // 选择完成，发送预中奖通知
            Activity::sendConfirmMessage($activity, $participates);
        } catch (\Exception $e) {
            Log::emergency(LotteryDraw::class, ['act_id' => $act_id, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
        }
    }

}
